package logic

import (
	"2103A-server/user/internal/model"
	"2103A-server/user/internal/svc"
	"2103A-server/user/user"
	"context"
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpc"
	"google.golang.org/grpc/status"
	"io/ioutil"
	"net/http"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

// 声明请求参数
type Eid struct {
	Body   map[string]string `json:"body"`             // json 请求体，这里以 string 为例，你可以使用任意类型
	Header string            `header:"Authorization "` // 添加请求头
}
type EidResponse struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Result  struct {
		Name        string `json:"name"`
		Idcard      string `json:"idcard"`
		Res         string `json:"res"`
		Description string `json:"description"`
		Sex         string `json:"sex"`
		Birthday    string `json:"birthday"`
		Address     string `json:"address"`
	} `json:"result"`
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *user.RegisterRequest) (*user.LoginResponse, error) {
	// todo: add your logic here and delete this line

	// 用户注册之前、需要验证一下手机号是否注册
	//查询数据
	_, e := l.svcCtx.UserModel.FindOneByMobile(l.ctx, in.Mobile)
	// 判断返回结果
	if e == nil {
		return nil, status.Error(http.StatusNotFound, "手机号已存在")
	}
	// 密码md5加密
	originPassword := []byte(in.Password)
	md5Password := md5.Sum(originPassword)
	strPassword := hex.EncodeToString(md5Password[:]) //加密后的密码

	// 实名认证 判断真实姓名和身份证是否一致
	var eid Eid
	eid.Body = map[string]string{
		"test": "test",
	}
	eid.Header = "APPCODE 217d433b154d422ca51ef26b9275d46c"
	//https://eid.shumaidata.com/eid/check?idcard=350301******9422&name=%E5%86%AF%E5%AE%9D%E5%AE%9D
	url := fmt.Sprintf("%s?idcard=%s&name=%s", "https://eid.shumaidata.com/eid/check", in.IdCard, in.RealName)
	fmt.Println(url)
	resp, fail := httpc.Do(context.Background(), http.MethodPost, url, eid)
	if fail != nil {
		fmt.Println(fail.Error())
		return &user.LoginResponse{
			Msg: "第三方调用出错",
		}, nil
	}

	defer resp.Body.Close()
	var eidRsp EidResponse

	// 蒋响应结果转化字节类型
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
	}

	err = json.Unmarshal(b, &eidRsp)
	if err != nil {
		fmt.Println("JSON解析失败，错误信息为：", err)
	}
	fmt.Println(eidRsp)
	if eidRsp.Code != "0" || eidRsp.Result.Res != "1" {
		return &user.LoginResponse{
			Msg: "身份证和姓名不一致",
		}, nil
	}

	// 数据添加
	var data model.User
	data.Mobile = in.Mobile     //传递过来的参数
	data.Password = strPassword //传递过来的参数
	data.Eamil = in.Email       //传递过来的参数
	data.RealName = in.RealName //传递过来的参数
	data.IdCard = in.IdCard     //传递过来的参数
	res, err := l.svcCtx.UserModel.Insert(l.ctx, &data)
	if err != nil {
		return nil, status.Error(http.StatusBadRequest, "添加失败")
	}

	// 获取新添加的
	id, err := res.LastInsertId()
	if err != nil {
		return nil, status.Error(http.StatusBadRequest, "添加失败")
	}
	fmt.Println(id)

	return &user.LoginResponse{}, nil
}
